<template>
	<div class="userinfo">
		<div class="editavatar">
			<div>
				<el-upload
				    class="avatar-uploader"
					action="/api/system/common/upload"
					:show-file-list="false"
					:on-success="handleAvatarSuccess"
					:before-upload="beforeAvatarUpload"
					:headers="headers"
				  >
				   <el-avatar  v-if="form.avatar"  class="avatar"
				          :src="imageUrl"></el-avatar>
				    <el-avatar v-else  class="avatar"
				            src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"></el-avatar>
				</el-upload>
			</div>
			<span class="editavatartext">点击修改头像</span>
		</div>
		<el-form  size="small"  ref="ruleFormRef" :rules="rules" class="userInfoContent" :model="form" label-width="auto" style="max-width: 600px">
			<el-row>
				<el-col span="12">
					<el-form-item label="账号" prop="userName">
					  <el-input v-model="form.userName" disabled/>
					</el-form-item>
				</el-col>
				<el-col  span="12">
					<el-form-item label="昵称" prop="nickName">
					  <el-input v-model="form.nickName" autofocus>
              <template #prefix>
                <el-icon><UserFilled /></el-icon>
              </template>
            </el-input>
					</el-form-item>
				</el-col>
			</el-row>
		    <el-row>
		    	<el-col span="12">
		    		<el-form-item label="手机号" prop="phone">
		    		  <el-input v-model="form.phone" maxlength="11" type="number">
                <template #prefix>
                  <el-icon><Iphone /></el-icon>
                </template>
              </el-input>
		    		</el-form-item>
		    	</el-col>
		    	<el-col  span="12">
		    		<el-form-item label="邮箱" prop="email">
              <el-input v-model="form.email" >
                <template #prefix>
                  <el-icon class="el-input_icon">
                    <GoodsFilled></GoodsFilled>
                  </el-icon>
                </template>
              </el-input>
		    		</el-form-item>
		    	</el-col>
		    </el-row>
			<el-row style="justify-content: space-between;">
				<el-col  span="12">
					<el-form-item label="状态" prop="status">
					  <el-switch v-model="form.status" :disabled="form.id == 1"/>
					</el-form-item>
				</el-col>
				<el-col  span="12">
					<el-form-item label="性别" prop="sex">
					  <el-radio-group v-model="form.sex">
					    <el-radio value="1">男</el-radio>
					    <el-radio value="0">女</el-radio>
					  </el-radio-group>
					</el-form-item>
				</el-col>
			</el-row>
			<el-form-item label="部门"  prop="deptId">
			  <el-tree-select
				  :disabled="form.id == 1"
			      v-model="form.deptId"
			      :data="dataDept"
			      check-strictly
			      :render-after-expand="false"
            :default-expanded-keys="[form.deptId]"
        >
        </el-tree-select>
			</el-form-item>
			<el-form-item label="角色" prop="roleIds">
			  <el-select :disabled="form.id == 1" multiple v-model="form.roleIds" placeholder="请选择角色">
			    <el-option
					v-for="item in roleData"
					:key="item.id"
					:label="item.roleName"
					:value="item.id"/>
			  </el-select>
			</el-form-item>
		    <el-form-item label="备注" prop="remark">
		      <el-input v-model="form.remark" type="textarea" />
		    </el-form-item>
		    <el-form-item style="margin-top:40px;">
				<el-button disabled size="small"  plain icon="Edit"  style="margin-left:180px;margin-right:20px;" type="primary" @click="onSubmit(ruleFormRef)">保存</el-button>
				<el-button  disabled size="small"  plain icon="Refresh"  style="color: darkgray"  @click="resetForm(ruleFormRef)" >重置</el-button>
		    </el-form-item>
		</el-form>
	</div>
</template>
<script lang="ts" setup>
import { reactive,ref,onMounted } from 'vue'
import type {FormInstance, FormRules,UploadProps} from 'element-plus'
import  {ElMessage} from 'element-plus'
import {useUserStore} from '@/stores/user.ts'
import {treelist} from '@/api/dept.ts'
import {list} from '@/api/role.ts'
import {edit, loginInfo} from '@/api/user.ts'
import {User, UserFilled} from "@element-plus/icons-vue";

const imageUrl = ref('')

const handleAvatarSuccess: UploadProps['onSuccess'] = (
  response,
  uploadFile
) => {
	console.log("uploadFile.raw!"+uploadFile.raw!)
	console.log("response：：："+response.msg)
  imageUrl.value = URL.createObjectURL(uploadFile.raw!)
  form.avatar = response.data
  edit(form);
  getUserInfo()
}
const userStore = useUserStore();
const getUserInfo=()=>{
  loginInfo().then((res)=>{
    if(res.code === 200){
      userStore.setUserInfo(res.data)
    }
  })
}


const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {
  if (rawFile.type !== 'image/jpeg') {
    ElMessage.error('Avatar picture must be JPG format!')
    return false
  } else if (rawFile.size / 1024 / 1024 > 2) {
    ElMessage.error('Avatar picture size can not exceed 2MB!')
    return false
  }
  return true
}


const token = userStore.token
const headers = ref({
	'Authorization':token
})

interface RuleForm {
  id:any
  userName: string
  nickName: string
  avatar:string
  sex: string
  status: string
  email: string
  deptId: number
  remark: string
  roleIds: Array<Number>
  phone: number
}
const ruleFormRef = ref<FormInstance>()
const form = reactive<RuleForm>({
  id:null,	
  userName: '',
  nickName: '',
  avatar:'',
  sex: '',
  status: '',
  email: '',
  deptId: 0,
  remark: '',
  roleIds:  [],
  phone: 0,
})
const baseUrl = import.meta.env.VITE_API_URL
onMounted(()=>{
	console.log("用户信息2:"+userStore.userInfo.user.userName)
	if(userStore.userInfo != undefined){
		const userInfo = userStore.userInfo;
		const user = userInfo.user;
		// 给表单填充数据
		form.id = user.id
    if (user.avatar){
      imageUrl.value = baseUrl+user.avatar
      form.avatar=user.avatar
    }
		form.userName = user.userName
		form.nickName = user.nickName
		form.sex = user.sex
		form.email = user.email
		form.deptId = user.deptId
		form.roleIds=user.roleIds
		form.phone = user.phone
	}
	deptData();
	getRoleData();
})
const dataDept=ref([{value:0,label:'顶级部门'}])
const deptData=()=>{
	treelist().then((res)=>{
		if(res.code === 200){
			dataDept.value[0].children =  res.data
		}
	})
}
const roleData =ref([])
const getRoleData = ()=>{
	list().then((res)=>{
		if(res.code === 200){
			roleData.value = res.data;
		}
	})
}
const rules = reactive<FormRules<RuleForm>>({
	nickName:[{required:true,message:'昵称不能为空',trigger:'blur'},
			  { min: 3, max: 5, message: '长度请输入 3 - 5位', trigger: 'blur' }],
	deptId:[{required:true,message:'部门不能为空',trigger:'blur'}],
	roleId:[{required:true,message:'角色不能为空',trigger:'blur'}]
})


const onSubmit = (formEl: FormInstance | undefined) => {
  if(!formEl){
    return
  }
  formEl.validate(async(valid, fields) => {
    if (valid) {
      console.log('submit!')
      await edit(form);
      getUserInfo()
    } else {
      console.log('error submit!', fields)
    }
  })
}

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}

</script>

<style scoped>
	.userinfo{
		display: flex;
		align-content: center;
	}
	.editavatar{
		margin-left:10px;
	}
	.userInfoContent{
		margin-left: 30px;
		flex-shrink: 0;
	}
	.avatar{
	   width:60px;
	   height:60px;
	}
	.editavatartext{
		color:lightgray;
		font-size: 12px;
	}
</style>